<template>
  <div class="login-container">
    <div class="login-image">
      <!--<img :src="require('@/assets/images/login_content_img.png')" alt="">-->
      <!--<div ref="loginImage" />-->
      <svg-icon icon-class="login_content_img" />
    </div>
    <div class="login-box">
      <div class="login-type-switch">
        <svg-icon v-if="loginModel==='normal'" icon-class="loginMethodQr" @click="changeLoginMethod('qr')" />
        <svg-icon v-if="loginModel==='qr'" icon-class="loginMethodNormal" @click="changeLoginMethod('normal')" />
      </div>
      <el-form v-if="loginModel==='normal'" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
        <div class="login-tab">
          <a :class="loginType===1 ? 'active' : ''" class="item" @click="changeLoginType(1)">密码登录</a>
          <a v-if="$config.loginMobile==='1'" :class="loginType=== 2 ? 'active' : ''" class="item " @click="changeLoginType(2)">短信登录</a>
        </div>
        <div class="input-container">
          <template v-if="loginType===1">
            <el-form-item prop="username" label="用户名：">
              <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名" type="text" auto-complete="on" />
            </el-form-item>
            <el-form-item prop="password" label="密码：">
              <el-input :key="passwordType" ref="password" v-model="loginForm.password" show-password type="password" placeholder="请输入密码" auto-complete="on" @keyup.enter.native="handleLogin" />
            </el-form-item>
            <el-form-item prop="verificationCode" label="验证码：" class="flex-main">
              <image-captcha-code ref="captchaCode" v-model="loginForm.verificationCode" />
            </el-form-item>
          </template>

          <template v-if="loginType===2">
            <el-form-item prop="mobile" label="输入手机号：">
              <el-input v-model="loginForm.mobile" placeholder="请输入手机号" maxlength="11" type="text" auto-complete="on" />
            </el-form-item>
            <el-form-item prop="mobileVerificationCode" label="输入验证码：" class="flex-main">
              <verification-code
                v-model="loginForm.mobileVerificationCode"
                :code-device="loginForm.mobile"
                :check="true"
                check-action="userValidateExistByField"
                @checkCode="handleCheckCode" />
            </el-form-item>
          </template>
        </div>
        <el-button :loading="loading" size="medium" type="primary" class="login-btn" @click.native.prevent="handleLogin">登录</el-button>
        <div class="login-auto">
          <el-checkbox v-model="remeber">记住密码</el-checkbox>
          <div class="login-enter">
            <el-link :underline="false" style="margin-right:8px" @click="handleGo('password')">忘记密码</el-link>
            <template v-if="$config.registerUser==='1'">
              |
              <el-link :underline="false" @click="handleGo('register')">免费注册</el-link>
            </template>

          </div>
        </div>
        <div class="login-type-container">
          <div class="login-type-title">
            <span />
            <div>其他登录方式</div>
            <span />
          </div>
          <div class="login-other-type">
            <el-tooltip class="item" effect="dark" content="企业微信Web" placement="top">
              <el-link :underline="false" @click="handleThirdLogin('OAUTH_CHANNEL_WX_WORK_PAGE')">
                <svg-icon icon-class="loginTypeQYWX" />
              </el-link>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="企业微信网页" placement="top">
              <el-link :underline="false" @click="handleThirdLogin('OAUTH_CHANNEL_WX_WORK_WEB')">
                <svg-icon icon-class="loginTypeQYWX" />
              </el-link>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="微信" placement="top">
              <el-link :underline="false" @click="handleToBeDeveloped">
                <svg-icon icon-class="loginTypeWX" />
              </el-link>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="钉钉" placement="top">
              <el-link :underline="false" @click="handleThirdLogin('OAUTH_CHANNEL_DING_TALK')">
                <svg-icon icon-class="loginTypeDingDing" />
              </el-link>
            </el-tooltip>
          </div>
        </div>
      </el-form>
      <transition>
        <div v-if="loginModel==='qr'" class="login-qrcode">
          <div class="login-qrcode-title">扫码登录</div>
          <div class="qrcode-container">
            <div id="qrCode" ref="qrCodeDiv" />
            <template v-if="!isScanLogin">
              <template v-if="!qrCodeIsEffective">
                <div class="qrcode-mask" />
                <div class="qrcode-outdate" style="display: block;">
                  <p class="qrcode-status">当前二维码已过期</p>
                  <a class="qrcode-refresh" @click="generateLoginQRCode"><i class="el-icon-refresh" />刷新二维码</a>
                </div>
              </template>

            </template>
            <template v-if="isScanLogin">
              <div class="qrcode-mask" />
              <div class="qrcode-outdate" style="display: block;">
                <p class="qrcode-status">扫描成功</p>
                <p class="qrcode-status">登录中</p>
              </div>
            </template>
          </div>
          <div class="qrcode-tip">
            请使用<span class="download-highlight"><a href="https://cdn-chiship.oss-cn-beijing.aliyuncs.com/default/chiship-framework-simple.apk" target="_blank">快速开发框架手机端</a></span>扫码
          </div>
        </div>
      </transition>

    </div>
  </div>
</template>

<script>
import demoLottie from '@/assets/lottie/demo.js'
import { setToken } from '@/utils/auth'
import QRCode from 'qrcodejs2'
export default {
  name: 'Login',
  data() {
    return {
      loginModel: 'normal',
      remeber: true,
      loginType: 1,
      loginForm: {
        username: '',
        password: '',
        mobile: '',
        verificationCode: '',
        mobileVerificationCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        verificationCode: [
          { required: true, trigger: 'blur', message: '请输入图形验证码' },
          { min: 4, max: 4, message: '请输入4位长度的图形验证码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '请输入手机号' },
          { validator: this.$validate.validateMobile, trigger: 'blur' }

        ],
        mobileVerificationCode: [
          { required: true, trigger: 'blur', message: '请输入手机验证码' },
          { min: 6, max: 6, message: '请输入6位长度的手机验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      verificationCodeText: '获取验证码',
      qrCodeIsEffective: true,
      qrCodeImageId: null,
      qrCodeIntervel: null,
      isScanLogin: false
    }
  },
  //
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    const errorMsg = this.$route.query && this.$route.query.errorMsg
    if (errorMsg) {
      this.$alert(errorMsg, '授权错误', {
        confirmButtonText: '确定',
        callback: action => {
          window.location.href = this.T.getUrl()
        }
      })
    }
    this.checkRemeber()
    this.generateLoginQRCode()
    this.loginType = 1
    document.onkeydown = (e) => {
      const key = window.event.keyCode
      if (key === 13) {
        this.handleLogin()
      }
    }
    this.$nextTick(() => {
      // this.loadAnimation()
    })
  },
  destroyed() {
    if (this.qrCodeIntervel) {
      clearInterval(this.qrCodeIntervel)
    }
  },
  methods: {
    loadAnimation() {
      this.$lottie.loadAnimation({
        container: this.$refs.loginImage,
        renderer: 'svg',
        loop: true,
        autoplay: true,
        animationData: demoLottie
      })
    },
    checkRemeber() {
      if (this.remeber === true) {
        try {
          var remberUser = localStorage.getItem('remberUser')
          if (remberUser) {
            remberUser = JSON.parse(remberUser)
            this.loginForm = {
              ...this.loginForm,
              username: remberUser.username,
              password: remberUser.password,
              mobile: remberUser.mobile
            }
          }
        } catch (err) {
          console.log(err)
        }
      }
    },
    changeLoginMethod(val) {
      if (val === 'qr' && this.$config.loginScan === '0') {
        this.$modal.msgWarning('未开启扫码登录！')
        return
      }
      this.loginModel = val
      if (val === 'qr') {
        this.loginType = 3
        this.generateLoginQRCode()
      } else {
        this.loginType = 1
        if (this.qrCodeIntervel) {
          clearInterval(this.qrCodeIntervel)
        }
      }
    },
    handleGo(url) {
      this.$router.push({ path: '/' + url })
    },
    generateLoginQRCode() {
      this.qrCodeIsEffective = true
      this.$store.dispatch('generateLoginQRCode').then((res) => {
        this.qrCodeImageId = res.imageId
        document.getElementById('qrCode').innerHTML = ''
        new QRCode(this.$refs.qrCodeDiv, {
          text: res.qrCode,
          width: 160,
          height: 160,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
        this.getQRImageStatus()
      }).catch((_) => {
      })
    },

    getQRImageStatus() {
      this.qrCodeIntervel = setInterval(() => {
        if (this.qrCodeImageId) {
          this.$store.dispatch('getQRImageStatus', { imageId: this.qrCodeImageId, loading: false }).then((res) => {
            var code = res.code
            if (code === -1) {
              this.qrCodeIsEffective = false
              if (this.qrCodeIntervel) {
                clearInterval(this.qrCodeIntervel)
              }
            }
            if (code === 1) {
              this.isScanLogin = true
            }
            if (code === 2) {
              setToken(res.token)
              this.$modal.msgSuccess('扫码登陆成功!')
              setTimeout(() => {
                window.location.reload()
              }, 2000)
            }
          }).catch((_) => {
            this.qrCodeIsEffective = false
            if (this.qrCodeIntervel) {
              clearInterval(this.qrCodeIntervel)
            }
          })
        }
      }, 3000)
    },
    changeLoginType(type) {
      this.$refs['loginForm'].clearValidate()
      this.loginType = type
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleCheckCode(val) {
      if (val) {
        this.handleLogin()
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (this.remeber === true) {
            localStorage.setItem('remberUser', JSON.stringify({
              username: this.loginForm.username,
              password: this.loginForm.password,
              mobile: this.loginForm.mobile
            }))
          } else {
            localStorage.removeItem('remberUser')
          }
          this.loading = true
          var user = Object.assign({}, this.loginForm)
          if (this.loginType === 1) {
            this.$store.dispatch('login', user).then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
              this.$modal.msgSuccess(this.T.getTimeState() + '好，欢迎回来！')
            }).catch(() => {
              this.$nextTick(() => {
                this.$refs.captchaCode.getCaptchaCode()
              })
              this.loginForm = {
                ...this.loginForm,
                verificationCode: ''
              }
              this.loading = false
            })
          }
          if (this.loginType === 2) {
            this.$store.dispatch('mobileLogin', user).then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
              this.$modal.msgSuccess(this.T.getTimeState() + '好，欢迎回来！')
            }).catch(() => {
              this.loading = false
              this.loginForm = {
                ...this.loginForm,
                mobileVerificationCode: ''
              }
            })
          }
        } else {
          return false
        }
      })
    },
    handleThirdLogin(channel) {
      this.$store.dispatch('thirdOauth2Auth', {
        callback: encodeURIComponent(this.T.getUrl() + '/#/login'),
        oauthChannel: channel
      }).then(res => {
        console.log(res)
        window.location.href = res
      })
    }
  }
}
</script>
<style lang="scss">
.v-enter,.v-leave-to {
  opacity: 0; /*点击按钮页面即将被显示，此时div标签处于隐藏状态*/
}
.v-enter-active,.v-leave-active  {
  transition: opacity 1s; /* 对该CSS样式进行transition的监控,有3s的过渡*/
}
.login-container {
  .el-form-item {
    margin-bottom: 11px;
    .el-form-item__label{
      color: #858585;
      font-weight: normal;
    }
  }
  .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before, .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before{
    content:''
  }
  .el-input {
    input {
      height: 36px;
      border-radius: 2px;
    }
  }
}
</style>
<style lang="scss" scoped>
  .login-container{
    display: flex;
    flex-direction: row;
    height: 100%;
    width: 100%;
    .login-image{
      width: 500px;
      margin-right: 75px;
      flex: 1;
      img{
        width: 500px;
        height: 500px;
      }
      .svg-icon{
        width: 500px;
        height: 500px;
      }
    }
    .login-box{
      position: relative;
      box-sizing: border-box;
      width: 451px;
      height: 620px;
      background: #ffffff;
      box-shadow: 0px 73px 80px rgba(112, 155, 219, 0.07), 0px 23.5744px 26.3871px rgba(112, 155, 219, 0.0521828), 0px 7.54093px 11.8229px rgba(112, 155, 219, 0.0464996), 0px 0.947239px 5.50447px rgba(112, 155, 219, 0.041707), 0px -1.44991px 2.3046px rgba(112, 155, 219, 0.0350554), 0px -1.48257px 0.686817px rgba(0, 0, 0, 0.0235958);
      border-radius: 8px;
      margin: 0 auto;
      border: 1px solid #f1f2f2;
      background-color: #fff;
      box-shadow: 0 0 18px 0 rgba(57, 141, 238, 0.12);
      .login-type-switch{
        position: absolute;
        top: 4px;
        right: 4px;
        width: 54px;
        height: 54px;
        cursor: pointer;
        .svg-icon{
          width: 54px;
          height: 54px;
        }
      }
      .login-form{
        padding: 30px 60px;
        .login-tab{
          display: flex;
          justify-content: space-around;
          margin: 10px 0 10px;
          align-items: center;
          height: 58px;
          font-size: 18px;
          text-align: center;
          line-height: 58px;
          color: rgba(0, 0, 0, 0.65);
          .item.active  {
            color:var(--color-primary);
          }
        }
        .input-container{
          height: 265px;
        }
        .login-btn{
          width: 100%;
          height: 44px;
          margin-bottom: 12px;
          margin-top: 12px;
        }
        .login-auto{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          font-size: 12px;
          position: relative;
          margin-top: 10px;
          margin-bottom: 20px;
          .login-enter {
            display: flex;
            align-items: center;
            color: #7A8599;
            a {
              font-size: 14px;
              color: #7A8599;
              margin-left: 8px;
            }
            a:first-child {
              margin: 0 8px 0 0;
            }
          }
        }
        .login-type-container{
          .login-type-title{
            display: flex;
            justify-content: space-between;
            margin: 0 auto;
            span {
              width: 100px;
              border-bottom: 1px solid #4E5A70;
              opacity: 0.1;
            }
            div {
              font-style: normal;
              font-weight: normal;
              font-size: 12px;
              line-height: 17px;
              color: #7A8599;
              opacity: 0.4;
              transform: translateY(8px);
            }
          }
          .login-other-type{
            display: flex;
            justify-content: center;
            margin-top: 20px;
            a{
              margin-left: 32px;
            }
            a:first-child{
              margin-left: 0px;
            }
            .svg-icon{
              display: block;
              width: 32px;
              height: 32px;
              box-sizing: border-box;
              cursor: pointer;
            }
          }
        }
      }
      .login-qrcode{
        position: absolute;
        top: 60px;
        left: 0;
        right: 0;
        bottom: 0;
        background: #fff;
        .login-qrcode-title{
          display: flex;
          justify-content: center;
          font-weight: 500;
          margin-top: 44px;
          font-size: 24px;
          line-height: 32px;
          color: #232D47;
        }
        .qrcode-container{
          box-sizing: border-box;
          width: 180px;
          height: 180px;
          position: relative;
          margin: 40px auto 20px;
          text-align: center;
          border: 1px solid #e6e7ea;
          border-radius: 3px;
          #qrCode{
            margin-top: 10px;
            margin-left: 10px;
            width: 160px;
            height: 160px;
          }
          .qrcode-mask {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            opacity: .8;
          }
          .qrcode-outdate {
            display: none;
            position: absolute;
            top: 35%;
            left: 0;
            right: 0;
            margin-top: -31px;
            z-index: 10;
            .qrcode-status {
              color: #fff;
              font-size: 14px;
            }
            .qrcode-refresh {
              display: block;
              width: 120px;
              height: 30px;
              line-height: 30px;
              border-radius: 60px;
              margin: 11px auto 0;
              background-size: 16px,16px;
              background-color: #3f8bfd;
              background-position: 12px;
              font-size: 14px;
              color: #fff;
              cursor: pointer;
              i{
                font-size: 15px;
                margin-right: 5px;
              }
            }
          }
        }
        .qrcode-tip{
          text-align: center;
          font-size: 14px;
          color: #91959e;
          .download-highlight{
            color: #3f8bfd;
            padding: 0 5px;
            cursor: pointer;
          }
        }
      }
    }

  }
</style>
